package com.wxg.test.interceptor;

import com.wxg.test.entity.FastPrincipal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;


/**
 * @Author hezhan
 * @Date 2019/9/25 15:25
 * 客户端渠道拦截适配器
 */
@Slf4j
public class UserInterceptor implements ChannelInterceptor {

    /**
     * 获取包含在stomp中的用户信息
     */
    public Message<?> preSend(Message<?> message, MessageChannel channel){
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        List<String> list = accessor.getNativeHeader("name");
        List<String> tokens = accessor.getNativeHeader("token");
        log.info("header获取的token信息:{},name信息:{}", CollectionUtils.isEmpty(list) ? null : tokens.get(0),
                CollectionUtils.isEmpty(list) ? null : list.get(0));
        if (StompCommand.CONNECT.equals(accessor.getCommand())){
            String userName = accessor.getNativeHeader("name").get(0);
            accessor.setUser(new FastPrincipal(userName));
        }
        return message;
    }
}
